package com.hero.part.boot.filter;

import org.pac4j.core.config.Config;
import org.pac4j.core.context.J2EContext;
import org.pac4j.core.engine.DefaultSecurityLogic;
import org.pac4j.core.engine.SecurityLogic;
import org.springframework.util.Assert;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yuez
 * @date 2018/3/5
 */
public class SecurityInterceptor extends HandlerInterceptorAdapter{

	private SecurityLogic<Boolean,J2EContext> scurityLogic = new DefaultSecurityLogic<>();

	private String clients;

	private String authorizers;

	private String matchers;

	private Boolean multiProfile;

	private Config config;

	public SecurityInterceptor(final Config config) {
		this.config = config;
	}

	public SecurityInterceptor(final String clients, final Config config) {
		this(config);
		this.clients = clients;
	}

	public SecurityInterceptor(String clients, String authorizers, Config config) {
		this(clients,config);
		this.authorizers = authorizers;
	}

	public SecurityInterceptor(String clients, String authorizers, String matchers, Config config) {
		this(clients,authorizers,config);
		this.matchers = matchers;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Assert.notNull(scurityLogic,"SecurityLogic is not null");
		Assert.notNull(config,"Config is not null");

		final J2EContext context = new J2EContext(request,response,config.getSessionStore());

		return scurityLogic.perform(context,config,
				(ctx,parameters) -> true,(code,webCtx) -> false,
				clients,authorizers,matchers,multiProfile);
	}

	public SecurityLogic<Boolean, J2EContext> getScurityLogic() {
		return scurityLogic;
	}

	public void setScurityLogic(SecurityLogic<Boolean, J2EContext> scurityLogic) {
		this.scurityLogic = scurityLogic;
	}

	public String getClients() {
		return clients;
	}

	public void setClients(String clients) {
		this.clients = clients;
	}

	public String getAuthorizers() {
		return authorizers;
	}

	public void setAuthorizers(String authorizers) {
		this.authorizers = authorizers;
	}

	public String getMatchers() {
		return matchers;
	}

	public void setMatchers(String matchers) {
		this.matchers = matchers;
	}

	public Boolean getMultiProfile() {
		return multiProfile;
	}

	public void setMultiProfile(Boolean multiProfile) {
		this.multiProfile = multiProfile;
	}

	public Config getConfig() {
		return config;
	}

	public void setConfig(Config config) {
		this.config = config;
	}
}
